import React, { useEffect, useRef, useState } from "react"
import NavTop from "./NavTop"
import { MoreOutline } from "antd-mobile-icons"
import "./ArticleDetail.scss"
import { useDispatch, useSelector } from "react-redux"
import {
  getArticleDetail,
  LiveActive,
  collecteActive,
  getCommentList,
  Follow
} from "../store/actions"
import { Toast, Popup } from "antd-mobile"
import { Icon } from "../components/Icon"
// 代码高亮
import highlight from "highlight.js"
import "highlight.js/styles/github-dark.css"
import dayjs from "dayjs"
// 导入中文语言包
import "dayjs/locale/zh-cn"
import DOMPurify from "dompurify"
import QQ from "../assets/images/share-sheet-qq.png"
import WX from "../assets/images/share-sheet-wechat.png"
import PYQ from "../assets/images/share-sheet-wechat-moments.png"
import WB from "../assets/images/share-sheet-weibo.png"
import Comment from "../components/Comment"
import CommentItem from "../components/CommentItem"
// 设置语言为中文
dayjs.locale("zh-cn")
function ArticleDetail(props) {
  const dispatch = useDispatch()
  const articleId = props.match.params.id
  const [visible, setVisible] = useState(false)
  // 可视区ref
  const wrapperRef = useRef()
  // 评论区ref
  const commentRef = useRef()
  // 是否已经显示评论区
  const isShowWrapper = useRef(false)
  // 评论模块
  const [commentVisible, setCommentVisible] = useState(false)
  useEffect(() => {
    // 获取文章详情并存如redux中
    dispatch(getArticleDetail(articleId))
    // 获取品论列表
    dispatch(getCommentList({ type: "a", source: articleId }))
  }, [dispatch, articleId])
  // 从redux中获取文章详情  // 从redux中获取评论列表
  const { detail, comment } = useSelector((state) => state.article)

  // 处理代码高亮
  useEffect(() => {
    const dgHtmlDOM = document.querySelector(".dg-html")
    const codes = dgHtmlDOM?.querySelectorAll("pre code")
    if (codes && codes.length > 0) {
      codes.forEach((el) => {
        // 让每个 code 内容实现代码高亮
        highlight.highlightElement(el)
      })
      return
    }

    highlight.configure({
      // 忽略警告
      ignoreUnescapedHTML: true
    })

    // 直接找到所有的 pre 标签
    const pres = dgHtmlDOM?.querySelectorAll("pre")
    if (pres && pres.length > 0) {
      pres.forEach((el) => {
        highlight.highlightElement(el)
      })
    }
  }, [detail])

  // 对文章点赞
  const handleLike = async () => {
    await dispatch(LiveActive(articleId, detail.attitude))
    Toast.show({
      content: detail.attitude === 1 ? "已取消点赞" : "已点赞",
      duration: 800
    })
  }
  // 收藏文章
  const handlecllected = async () => {
    await dispatch(collecteActive(articleId, detail.is_collected))
    Toast.show({
      content: detail.is_collected ? "已取消收藏" : "已收藏",
      duration: 800
    })
  }
  // 点击显示评论
  const onShowComment = () => {
    const comment = commentRef.current
    const wrapper = wrapperRef.current
    const isShowW = isShowWrapper.current
    const commentTop = comment.getBoundingClientRect().top

    // 没有显示评论区
    if (!isShowW) {
      wrapper.scrollTo({
        top: commentTop - 46 + wrapper.scrollTop,
        behavior: "auto"
      })
    } else {
      wrapper.scrollTo(0, 0)
    }

    isShowWrapper.current = !isShowW
  }
  // 关注
  const toggleFollow = () => {
    dispatch(Follow(detail.aut_id, detail.is_followed))
  }
  return (
    <div>
      <NavTop>
        <div className="more">
          <MoreOutline />
        </div>
      </NavTop>
      {/* <NavTop></NavTop> */}
      <div className="comment" ref={wrapperRef}>
        <div className="article-header">
          <h3>{detail.title}</h3>
          <p className="num">
            <span>{dayjs(detail.pubdate).format("YYYY年MM月DD日")} |</span>
            <span>{detail.read_count}阅读 |</span>
            <span>{detail.comm_count}评论</span>
          </p>
          <div className="author">
            <div>
              <img
                src={
                  detail.aut_photo ||
                  "http://geek.itheima.net/images/user_head.jpg "
                }
                alt=""
              ></img>
            </div>
            <p>{detail.aut_name}</p>
            {detail.is_followed ? (
              <button className="followed" onClick={() => toggleFollow()}>
                已关注
              </button>
            ) : (
              <button className="follow" onClick={() => toggleFollow()}>
                +关注
              </button>
            )}
          </div>
        </div>
        <div className="content">
          {/* 不依赖script标签渲染html，删除弹框等事件 */}
          <div
            className="content-html dg-html"
            dangerouslySetInnerHTML={{
              __html: DOMPurify.sanitize(detail.content)
            }}
          />

          <div className="time">
            发布文章时间: {dayjs(detail.pubdate).format("YYYY年MM月DD日")}
          </div>
        </div>
        <div className="space"></div>
        <div className="commentList" ref={commentRef}>
          <div>
            <div className="comment-title">
              <span className="commentCount">
                全部评论 ({comment.total_count || 0})
              </span>
              <span className="commentLove">0 点赞</span>
            </div>
            {comment?.total_count === 0 ? (
              <div className="none">
                <img
                  src="http://geek.itheima.net/dist/img/none.21d1f2fd.png"
                  alt=""
                ></img>
                <p>还没有人评论哦</p>
              </div>
            ) : (
              <div>
                {comment.results?.map((item) => {
                  return (
                    <CommentItem key={item.com_id} comment={item}></CommentItem>
                  )
                })}
                <div className="last">没有更多了</div>
              </div>
            )}
          </div>
        </div>
      </div>
      <div className="comment-bottom">
        <div className="input-btn" onClick={() => setCommentVisible(true)}>
          <Icon type="iconbianji" />
          <span>抢沙发</span>
        </div>
        <Popup
          visible={commentVisible}
          onMaskClick={() => {
            setCommentVisible(false)
          }}
          bodyStyle={{ height: "100%" }}
        >
          <Comment
            articleId={articleId}
            closeModel={() => {
              setCommentVisible(false)
            }}
          />
        </Popup>
        <div className="action-item" onClick={onShowComment}>
          <Icon type="iconbtn_comment" />
          <p>评论</p>
          {comment.total_count !== 0 && (
            <span className="badage">{comment.total_count}</span>
          )}
        </div>
        <div className="action-item" onClick={handleLike}>
          <Icon
            type={detail.attitude === 1 ? "iconbtn_like_sel" : "iconbtn_like2"}
          />
          <p>点赞</p>
        </div>
        <div className="action-item" onClick={handlecllected}>
          <Icon
            type={
              detail.is_collected ? "iconbtn_collect_sel" : "iconbtn_collect"
            }
          />
          <p>收藏</p>
        </div>
        <div className="action-item" onClick={() => setVisible(true)}>
          <Icon type="iconbtn_share" />
          <p>分享</p>
        </div>

        <Popup
          className="comment-popup"
          position="bottom"
          visible={visible}
          onMaskClick={() => {
            setVisible(false)
          }}
        >
          <div className="popupTitle">立即分享给好友</div>
          <div className="share">
            <div>
              <img src={WX} alt=""></img>
              <p>微信</p>
            </div>
            <div>
              <img src={PYQ} alt=""></img>
              <p>朋友圈</p>
            </div>
            <div>
              <img src={WB} alt=""></img>
              <p>微博</p>
            </div>
            <div>
              <img src={QQ} alt=""></img>
              <p>QQ</p>
            </div>
          </div>
          <div className="share">
            <div>
              <img
                src="https://img01.yzcdn.cn/vant/share-sheet-link.png"
                alt=""
              ></img>
              <p>复制链接</p>
            </div>
            <div>
              <img
                src="https://img01.yzcdn.cn/vant/share-sheet-poster.png"
                alt=""
              ></img>
              <p>分享海报</p>
            </div>
            <div>
              <img
                src="https://img01.yzcdn.cn/vant/share-sheet-qrcode.png"
                alt=""
              ></img>
              <p>二维码</p>
            </div>
            <div>
              <img
                src="https://img01.yzcdn.cn/vant/share-sheet-weapp-qrcode.png"
                alt=""
              ></img>
              <p>小程序码</p>
            </div>
          </div>
          <div className="line"></div>
          <button
            onClick={() => {
              setVisible(false)
            }}
          >
            取消
          </button>
        </Popup>
      </div>
    </div>
  )
}

export default ArticleDetail
